package com.yupi.springbootinit.utils;

import com.alibaba.excel.EasyExcel;
import com.yupi.springbootinit.listener.ExcelListener;
import com.yupi.springbootinit.model.entity.ExcelData;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.formula.functions.T;
import org.springframework.util.CollectionUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * Excel 相关工具类
 */
@Slf4j
public class ExcelUtils {

    public static String excelToCsv(File file, ExcelListener excelLinstener){

        try {
            EasyExcel.read(new FileInputStream(file), null, excelLinstener).sheet().doRead();
        } catch (IOException e) {
            log.info("表格处理错误");
        }
        //表头数据
        Map<Integer,String> map = excelLinstener.getMap();
        //表数据
        List<Map<String,Object>> cachedDataList = excelLinstener.getCachedDataList();
        if(CollectionUtils.isEmpty(cachedDataList)||map==null){
            return "";
        }

        //转化为csv文件
        StringBuilder stringBuilder = new StringBuilder();
        //header头拼接
        List<String> headerList = map.values().stream().collect(Collectors.toList());
        stringBuilder.append(StringUtils.join(headerList, ",")).append("\n");
        //数据拼接
        List<List<Object>> totalList = new ArrayList<>();

        for (Map<String, Object> entityMap : cachedDataList) {
            List<Object> collect = entityMap.values().stream().collect(Collectors.toList());
            totalList.add(collect);
        }
        for (List<Object> objects : totalList) {
            stringBuilder.append(StringUtils.join(objects,",")).append("\n");
        }
        return stringBuilder.toString();
    }

    public static void main(String[] args) throws IllegalAccessException {
    }









    //        for (T excelData : cachedDataList) {
//            Field[] declaredFields = excelData.getClass().getDeclaredFields();
//            List<Object> list = new ArrayList<>();
//            for (Field declaredField : declaredFields) {
//                try {
//                    declaredField.setAccessible(true);
//                    Object value = declaredField.get(excelData);
//                    list.add(value);
//                } catch (IllegalAccessException e) {
//                    e.printStackTrace();
//                }
//            }
//            totalList.add(list);
//        }
}
